﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using CE.Global;
using CE.User;

public partial class car_insurance_sign_in_auto : MyLanguageBasePage
{
    string _redirectUrl = "";
    string rowGuid = "";
    Int64 carId = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (isMobileBrowser())
            {
                string mobileurl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MobileURL");
               
                if (Request.QueryString["uid"] != null && Request.QueryString["uid"].ToString() != ""
                && Request.QueryString["carid"] != null && Request.QueryString["carid"].ToString() != "")
                {
                    rowGuid = Request.QueryString["uid"].ToString();
                    Int64 _tempCarID = 0;

                    if (Int64.TryParse(Request.QueryString["carid"].ToString(), out _tempCarID))
                    {
                        carId = _tempCarID;
                        mobileurl += "/Login-auto.aspx?" + (Request.QueryString["lng"] != null ? "lng=" + Request.QueryString["lng"].ToString() : "") + "&uid=" + rowGuid + "&carid=" + carId;
                    }
                }

                Response.Redirect(mobileurl);

            }

            if (Request.QueryString["lng"] != null && Request.QueryString["lng"] == "e")
                Session["Language"] = "en-US";
            if (Request.QueryString["uid"] != null && Request.QueryString["uid"].ToString() != ""
                && Request.QueryString["carid"] != null && Request.QueryString["carid"].ToString() != "")
            {
                rowGuid = Request.QueryString["uid"].ToString();
                Int64 _tempCarID = 0;

                if (Int64.TryParse(Request.QueryString["carid"].ToString(), out _tempCarID))
                {
                    carId = _tempCarID;
                }
                else
                {
                    Response.Redirect("sign-in.aspx");
                }

                Page.Validate("excustomer");
                if (Page.IsValid)
                {
                    AutoLogin(200);
                    Response.Redirect("sign-in.aspx");
                }
                else
                    Response.Redirect("sign-in.aspx");
            }
            else
                Response.Redirect("/" + (Request.QueryString["lng"] != null && Request.QueryString["lng"] == "e" ? "/en/home.aspx" : ""));
        }
        else
            Response.Redirect("/" + (Request.QueryString["lng"] != null && Request.QueryString["lng"] == "e" ? "/en/home.aspx" : ""));
    }

    private void AutoLogin(int LoginType)
    {

        AccountStatus _accountstatus = new AccountStatus();
        AccountStatusDB _accountstatusdb = new AccountStatusDB();
        AccountDB _accountdb = new AccountDB();
        //Check Customer Account
        Account _account = _accountdb.GetUserLoginFromMailByGUID(rowGuid, carId, 1);

        if (_account != null)
        {
            _accountstatus = _accountstatusdb.GetAccountStatus(_account.CEID, 400);

            if (_account.Status == true)
            {
                Int64 _userResultId = Convert.ToInt64(_account.UserResultId);
                Int64 _userId = Convert.ToInt64(_account.CEID);
                if (_account.Info1 == "0")
                {
                    //Reset Email Fail Message
                    _account.Info1 = "";
                    _account.Info2 = "";
                    _accountdb.Insert(_account);
                }

                _accountstatusdb.InsertAccountStatus(_account.CEID, 400, 1);
                //divExErrorMessage.Visible = false;
                GetUserInformation(_account);
                SaveUserLoginInformation(_account.CEID, _account.UserTypeId);
                CE.Global.General.CreateUpdateUserLoginCached(Page);
                _account = null;
                UserResultHistory _resulthis = new UserResultHistory();
                UserResultHistoryDB _resulthisdb = new UserResultHistoryDB();

                _resulthis = _resulthisdb.GetResultHistory(_userId, _userResultId);
                if (LoginType == 100)
                {
                    _redirectUrl = CE.Global.General.GetUrl("~/user/saved-quotes.aspx", Page);
                    Response.Redirect(_redirectUrl);
                }
                else
                {
                    if (Session[CE.Global.General.UserProfileAndContactComplete].ToString() == "1")
                    {
                        Session[General.CarId] = _resulthis.ID1.ToString();
                        Session[General.CarPolicyId] = _resulthis.ID2.ToString();
                        Session[General.IsCarRestoreResult] = "1";
                        Session["CLASSTYPE"] = null;
                        Session["IsFromAutoLogin"] = "1";
                        if (Session[General.CarId] != null)
                        {

                            if (Session["Language"].ToString() == "en-US")
                            {
                                Response.Redirect("~/en/car-insurance/quote-results.aspx");
                            }
                            else
                            {
                                Response.Redirect("~/car-insurance/quote-results.aspx");
                            }
                        }
                        else
                        {
                            if (Request.Params["type"] != null)
                            {
                                if (Request.Params["type"].ToString() == "view")
                                {
                                    _redirectUrl = CE.Global.General.GetUrl("~/user/saved-quotes.aspx", Page);
                                    Response.Redirect(_redirectUrl);
                                }
                                else if (Request.Params["type"].ToString() == "return")
                                {
                                    //Response.Redirect("car-and-policy-details.aspx");
                                    _redirectUrl = CE.Global.General.GetUrl("~/user/saved-quotes.aspx", Page);
                                    Response.Redirect(_redirectUrl);
                                }
                            }
                            else
                            {
                                if (Session["Language"].ToString() == "en-US")
                                {
                                    Response.Redirect("~/en/car-insurance/quote-results.aspx");
                                }
                                else
                                {
                                    Response.Redirect("~/car-insurance/quote-results.aspx");
                                }


                            }
                        }
                    }
                    else
                    {
                        _redirectUrl = CE.Global.General.GetUrl("~/user/saved-quotes.aspx", Page);
                        Response.Redirect(_redirectUrl);
                    }
                }
            }
            else
            {
                lblLoginMessage.Text = "Your email has been blocked!";
            }
        }
        else
        {
            lblLoginMessage.Text = Resources.Menu.EmailPasswordIncorrect;
        }
    }

    private bool CheckUserLoginCached(string UserId)
    {
        bool _retValue = false;
        string sKey = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.UserCacheName");
        sKey += UserId;
        if (HttpContext.Current.Cache[sKey] == null)
        {
            _retValue = true;
        }
        else
        {
            if (Session[General.UserId] == null)
            {
                this.Cache.Remove(sKey);
                _retValue = true;
            }
            else
            {
                _retValue = false;
            }
        }
        return _retValue;
    }

    private void GetUserInformation(Account _account)
    {
        DateTime dtNow = new DateTime();
        dtNow = General.GetUTCDateTime();
        Session[CE.Global.General.UserId] = _account.CEID;
        Session[CE.Global.General.UserTypeId] = _account.UserTypeId;

        if (_account.UserTypeId == Convert.ToInt32(CE.Global.CEUserType.Provider))
        {
            CE.Provider.ProviderCompanyLink _comlink = new CE.Provider.ProviderCompanyLink();
            CE.Provider.ProviderCompanyLinkDB _comlinkdb = new CE.Provider.ProviderCompanyLinkDB();
            _comlink = _comlinkdb.GetProviderCompanyId(_account.CEID);
            if (_comlink != null)
            {
                Session[CE.Global.General.ProviderCompanyId] = _comlink.ProviderCompanyId;
            }
        }

        Session[CE.Global.General.UserEmail] = _account.Email;
        Session[CE.Global.General.StartTime] = dtNow.ToString();
        bool isProfileComplete = false;
        bool isContactComplete = false;

        ProfileDB _profiledb = new ProfileDB();
        Profile _profile = new Profile();
        Contact _contact = new Contact();
        ContactDB _contactdb = new ContactDB();

        _contact = _contactdb.GetContact(_account.CEID);

        _profile = _profiledb.GetProfile(_account.CEID);

        if (_contact != null)
        {
            isContactComplete = true;
            Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
        }
        else
        {
            Session[CE.Global.General.UserPhoneNo] = null;
        }

        if (_profile != null)
        {
            if (_profile.FirstName != null && _profile.FirstName != string.Empty)
            {
                Session[CE.Global.General.UserName] = Server.HtmlDecode(_profile.FirstName) + " " + Server.HtmlDecode(_profile.SurName);
            }
            else
            {
                Session[CE.Global.General.UserName] = Server.HtmlDecode(_profile.SurName);
            }

            if (!string.IsNullOrEmpty(_profile.IDType) &&
                !string.IsNullOrEmpty(_profile.IDNo) &&
                _profile.IDNo.Length == 9)
            {
                Session[CE.Global.General.UserICNumber] = _profile.IDType + " " + _profile.IDNo;
            }

            if (_profile.Status.ToLower() == "complete")
            {
                isProfileComplete = true;
            }
            else
            {
                isProfileComplete = false;
            }
        }
        else
        {
            Session[CE.Global.General.UserName] = null;
        }

        if (isProfileComplete && isContactComplete)
        {
            Session[CE.Global.General.UserProfileAndContactComplete] = "1";
        }
        else
        {
            Session[CE.Global.General.UserProfileAndContactComplete] = "0";
        }

    }

    protected bool SaveUserLoginInformation(Int64 CEID, int UserTypeId)
    {
        LoginHistory _loghis = new LoginHistory();
        LoginHistoryDB _loghisdb = new LoginHistoryDB();
        LoginInformation _loginfo = new LoginInformation();
        LoginInformationDB _loginfodb = new LoginInformationDB();

        _loghis.CEID = CEID;
        _loghis.UserTypeId = UserTypeId;
        _loghis.StartTime = General.GetUTCDateTime();
        _loghis.EndTime = General.GetUTCDateTime();
        _loghis.IsExpired = false;
        _loghis.Status = "LOGIN";

        _loghis.LoginHisId = _loghisdb.Insert(_loghis);

        if (_loghis.LoginHisId > 0)
        {
            Session[CE.Global.General.LoginHistoryId] = _loghis.LoginHisId.ToString();
            _loginfo.CEID = CEID;
            _loginfo.UserTypeId = UserTypeId;
            _loginfo.LogHisId = _loghis.LoginHisId;
            _loginfo.Browser = Request.Browser.Browser;
            _loginfo.BrowserType = Request.Browser.Type;
            _loginfo.BrowserVersion = Request.Browser.Version;
            _loginfo.MajorVersion = Request.Browser.MajorVersion.ToString();
            _loginfo.MinorVersion = Request.Browser.MinorVersionString;
            _loginfo.JavaScript = Request.Browser.JavaScript;
            _loginfo.VBScript = Request.Browser.VBScript;
            _loginfo.ActivX = Request.Browser.ActiveXControls;
            _loginfo.Frames = Request.Browser.Frames;
            _loginfo.Tables = Request.Browser.Tables;
            _loginfo.Cookies = Request.Browser.Cookies;
            _loginfo.DotNetVersion = Request.Browser.ClrVersion.ToString();
            _loginfo.JavaApplet = Request.Browser.JavaApplets;
            _loginfo.Win16 = Request.Browser.Win16;
            _loginfo.Win32 = Request.Browser.Win32;
            _loginfo.Platform = Request.Browser.Platform;
            _loginfo.UserAgent = Request.UserAgent.ToString();
            _loginfo.IpAddress = Request.UserHostAddress;
            _loginfo.HostName = Request.UserHostName;

            _loginfo.UserInfoId = _loginfodb.Insert(_loginfo);
        }

        return _loginfo.UserInfoId > 0;

    }


    public static bool isMobileBrowser()
    {
        //GETS THE CURRENT USER CONTEXT
        HttpContext context = HttpContext.Current;

        //FIRST TRY BUILT IN ASP.NT CHECK
        if (context.Request.Browser.IsMobileDevice)
        {
            return true;
        }
        //THEN TRY CHECKING FOR THE HTTP_X_WAP_PROFILE HEADER
        if (context.Request.ServerVariables["HTTP_X_WAP_PROFILE"] != null)
        {
            return true;
        }
        //THEN TRY CHECKING THAT HTTP_ACCEPT EXISTS AND CONTAINS WAP
        if (context.Request.ServerVariables["HTTP_ACCEPT"] != null &&
            context.Request.ServerVariables["HTTP_ACCEPT"].ToLower().Contains("wap"))
        {
            return true;
        }
        //AND FINALLY CHECK THE HTTP_USER_AGENT 
        //HEADER VARIABLE FOR ANY ONE OF THE FOLLOWING
        if (context.Request.ServerVariables["HTTP_USER_AGENT"] != null)
        {
            //Create a list of all mobile types
            string[] mobiles =
                new[]
                {
                    "midp", "j2me", "avant", "docomo", 
                    "novarra", "palmos", "palmsource", 
                    "240x320", "opwv", "chtml",
                    "pda", "windows ce", "mmp/", 
                    "blackberry", "mib/", "symbian", 
                    "wireless", "nokia", "hand", "mobi",
                    "phone", "cdm", "up.b", "audio", 
                    "SIE-", "SEC-", "samsung", "HTC", 
                    "mot-", "mitsu", "sagem", "sony"
                    , "alcatel", "lg", "eric", "vx", 
                    "NEC", "philips", "mmm", "xx", 
                    "panasonic", "sharp", "wap", "sch",
                    "rover", "pocket", "benq", "java", 
                    "pt", "pg", "vox", "amoi", 
                    "bird", "compal", "kg", "voda",
                    "sany", "kdd", "dbt", "sendo", 
                    "sgh", "gradi", "jb", "dddi", 
                    "moto", "iphone"
                };

            //Loop through each item in the list created above 
            //and check if the header contains that text
            foreach (string s in mobiles)
            {
                if (context.Request.ServerVariables["HTTP_USER_AGENT"].ToLower().Contains(s.ToLower()))
                {
                    return true;
                }
            }
        }

        return false;
    }

}
